<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen p-[32rpx] box-border">
    <text class="block text-[56rpx] font-extrabold mb-[48rpx] text-center text-blue-600">服务对象个人基本信息</text>
    
    <nut-form ref="formRef" :model="form" :rules="formRules" class="max-w-[700rpx] w-full mx-auto box-border">
      <!-- 基本信息区域 -->
      <view class="bg-gray-50 rounded-[20rpx] p-[32rpx] mb-[40rpx] box-border">
        <text class="block text-[36rpx] font-bold mb-[32rpx] text-gray-700">📋 基本信息</text>
        
        <nut-form-item label="姓名" prop="姓名" class="mb-[32rpx] box-border text-[32rpx]">
          <nut-input 
            v-model="form.姓名" 
            placeholder="请输入姓名"
            class="h-[88rpx] text-[32rpx]"
            @blur="validateField('姓名')"
          />
        </nut-form-item>
        
        <nut-form-item label="身份证号码" prop="身份证号码" class="mb-[32rpx] box-border text-[32rpx]">
          <nut-input 
            v-model="form.身份证号码" 
            placeholder="请输入身份证号码"
            maxlength="18"
            class="h-[88rpx] text-[32rpx]"
            @input="onIdCardInput"
            @blur="validateField('身份证号码')"
          />
          <view v-if="idCardError" class="text-[28rpx] text-red-500 mt-[12rpx]">
            {{ idCardError }}
          </view>
        </nut-form-item>
      </view>
      
      <!-- 健康相关信息区域 -->
      <view class="bg-blue-50 rounded-[16rpx] p-[24rpx] mb-[32rpx] box-border">
        <text class="block text-[28rpx] font-bold mb-[24rpx] text-blue-700">🏥 健康相关信息</text>
        
        <nut-form-item label="电子健康码" prop="电子健康码" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.电子健康码" 
            placeholder="请输入电子健康码"
            @blur="validateField('电子健康码')"
          />
        </nut-form-item>
        
        <nut-form-item label="AnfinID" prop="AnfinID" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.AnfinID" 
            placeholder="请输入AnfinID"
            @blur="validateField('AnfinID')"
          />
        </nut-form-item>
        
        <nut-form-item label="健康档案编号" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.健康档案编号" 
            placeholder="请输入健康档案编号（选填）"
          />
        </nut-form-item>
        
        <nut-form-item label="个人健康服务凭证" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.个人健康服务凭证" 
            placeholder="请输入凭证（选填）"
          />
        </nut-form-item>
      </view>
      
      <!-- 其他证件信息区域 -->
      <view class="bg-green-50 rounded-[16rpx] p-[24rpx] mb-[32rpx] box-border">
        <text class="block text-[28rpx] font-bold mb-[24rpx] text-green-700">🆔 其他证件信息</text>
        
        <nut-form-item label="其他身份证件" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.其他身份证件" 
            placeholder="请输入其他身份证件（选填）"
          />
        </nut-form-item>
      </view>
      
      <!-- 会员信息区域 -->
      <view class="bg-purple-50 rounded-[16rpx] p-[24rpx] mb-[32rpx] box-border">
        <text class="block text-[28rpx] font-bold mb-[24rpx] text-purple-700">💳 会员信息</text>
        
        <nut-form-item label="在本机构的任意一份订单编号" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.在本机构的任意一份订单编号" 
            placeholder="请输入订单编号（选填）"
          />
        </nut-form-item>
        
        <nut-form-item label="会员卡号" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.会员卡号" 
            placeholder="请输入会员卡号（选填）"
          />
        </nut-form-item>
        
        <nut-form-item label="储值卡号" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.储值卡号" 
            placeholder="请输入储值卡号（选填）"
          />
        </nut-form-item>
        
        <nut-form-item label="积分卡号" class="mb-[24rpx] box-border">
          <nut-input 
            v-model="form.积分卡号" 
            placeholder="请输入积分卡号（选填）"
          />
        </nut-form-item>
      </view>
      
      <!-- 地址信息区域 -->
      <view class="bg-orange-50 rounded-[16rpx] p-[24rpx] mb-[32rpx] box-border">
        <text class="block text-[28rpx] font-bold mb-[24rpx] text-orange-700">📍 地址信息</text>
        
        <nut-form-item label="常住详细地址" prop="常住详细地址" class="mb-[24rpx] box-border">
          <nut-textarea 
            v-model="form.常住详细地址" 
            placeholder="请输入详细地址"
            rows="3"
            maxlength="200"
            show-word-limit
            @blur="validateField('常住详细地址')"
          />
        </nut-form-item>
      </view>
      
      <!-- 联系方式区域 -->
      <view class="bg-teal-50 rounded-[16rpx] p-[24rpx] mb-[32rpx] box-border">
        <text class="block text-[28rpx] font-bold mb-[24rpx] text-teal-700">联系方式</text>
        
        <nut-button 
          block 
          type="primary" 
          class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow-md bg-teal-500 border-teal-500 hover:bg-teal-600 active:bg-teal-700"
          @click="goTo('contact')"
        >
          <view class="flex items-center justify-center">
            <!-- <text class="text-white mr-[16rpx] text-[32rpx]">📱</text> -->
            <text class="text-white text-[32rpx]">填写联系方式</text>
          </view>
        </nut-button>
      </view>
      
      <!-- 操作按钮 -->
      <view class="mt-[48rpx] flex gap-[24rpx]">
        <nut-button 
          block 
          type="default" 
          class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1"
          @click="resetForm"
        >
          重置表单
        </nut-button>
        <nut-button 
          block 
          type="primary" 
          class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1 bg-green-500 hover:bg-green-600 active:bg-green-700"
          :loading="submitting"
          @click="submitForm"
        >
          {{ submitting ? '保存中...' : '保存信息' }}
        </nut-button>
      </view>
    </nut-form>
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro'
import { ref, reactive } from 'vue'
// import { 
//   Form as NutForm, 
//   FormItem as NutFormItem, 
//   Input as NutInput, 
//   Button as NutButton,
//   Textarea as NutTextarea
// } from '@nutui/nutui-taro'

/**
 * 服务对象个人基本信息表单数据
 * @typedef {Object} ServicePersonInfo
 * @property {string} 姓名
 * @property {string} 身份证号码
 * @property {string} 电子健康码
 * @property {string} AnfinID
 * @property {string} 健康档案编号
 * @property {string} 其他身份证件
 * @property {string} 个人健康服务凭证
 * @property {string} 在本机构的任意一份订单编号
 * @property {string} 会员卡号
 * @property {string} 储值卡号
 * @property {string} 积分卡号
 * @property {string} 常住详细地址
 */
const form = ref({
  姓名: '',
  身份证号码: '',
  电子健康码: '',
  AnfinID: '',
  健康档案编号: '',
  其他身份证件: '',
  个人健康服务凭证: '',
  在本机构的任意一份订单编号: '',
  会员卡号: '',
  储值卡号: '',
  积分卡号: '',
  常住详细地址: ''
})

const formRef = ref()
const submitting = ref(false)
const idCardError = ref('')

// 表单验证规则
const formRules = reactive({
  姓名: [
    { required: true, message: '请输入姓名' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间' }
  ],
  身份证号码: [
    { required: true, message: '请输入身份证号码' },
    { 
      validator: (value: string) => /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value), 
      message: '请输入正确的身份证号码格式' 
    }
  ],
  电子健康码: [
    { required: true, message: '请输入电子健康码' }
  ],
  AnfinID: [
    { required: true, message: '请输入AnfinID' }
  ],
  常住详细地址: [
    { required: true, message: '请输入常住详细地址' },
    { min: 5, max: 200, message: '地址长度应在5-200个字符之间' }
  ]
})

// 身份证号输入验证
const onIdCardInput = (value: string) => {
  idCardError.value = ''
  
  // 只允许数字和X
  const validValue = value.replace(/[^\dXx]/g, '').toUpperCase()
  if (validValue !== value) {
    form.value.身份证号码 = validValue
  }
  
  // 验证格式
  if (validValue && validValue.length >= 15) {
    if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X)$)/.test(validValue)) {
      idCardError.value = '请输入正确的身份证号码格式'
    }
  }
}

// 字段验证（兼容没有 validateField 的场景）
const validateField = async (fieldName: string) => {
  if (!formRef.value) return true
  const maybeForm: any = formRef.value
  if (typeof maybeForm.validateField === 'function') {
    return maybeForm.validateField(fieldName)
  }
  if (typeof maybeForm.validate === 'function') {
    return maybeForm.validate()
  }
  return true
}

// 重置表单
const resetForm = () => {
  Taro.showModal({
    title: '确认重置',
    content: '确定要重置表单吗？所有已填写的信息将被清空。',
    success: (res) => {
      if (res.confirm) {
        form.value = {
          姓名: '',
          身份证号码: '',
          电子健康码: '',
          AnfinID: '',
          健康档案编号: '',
          其他身份证件: '',
          个人健康服务凭证: '',
          在本机构的任意一份订单编号: '',
          会员卡号: '',
          储值卡号: '',
          积分卡号: '',
          常住详细地址: ''
        }
        idCardError.value = ''
        
        Taro.showToast({
          title: '表单已重置',
          icon: 'success',
          duration: 1500
        })
      }
    }
  })
}

// 表单提交
const submitForm = async () => {
  try {
    submitting.value = true
    
    await formRef.value.validate()
    
    // 清除错误信息
    idCardError.value = ''
    
    // 模拟提交延迟
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 显示成功提示
    Taro.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000
    })
    
    // 这里可以添加实际的保存逻辑
    console.log('服务对象个人信息:', form.value)
    
  } catch (error) {
    // 显示错误提示
    Taro.showToast({
      title: '请完善必填信息',
      icon: 'error',
      duration: 2000
    })
  } finally {
    submitting.value = false
  }
}

function goTo(subPage: string) {
  Taro.navigateTo({
    url: subPage
  })
}
</script>

<style lang="scss">
.nut-cell-group__wrap{
  box-shadow: none !important;
}
</style>